package model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-29
 * Time：08:29
 */
public class FollowerDao  {
    public void insert(Follower follower) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL语句
            String sql = "insert into followers values(null, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, follower.getUserId());
            statement.setInt(2, follower.getFollowerUserId());
            //3.执行sql
            int ret = statement.executeUpdate();
            if (ret == 1) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    public List<Integer> selectFollowers(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Integer> userIdList = new ArrayList<>();
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL语句
            String sql = "select * from followers where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Integer uId = resultSet.getInt("followerUserId");
                userIdList.add(uId);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return userIdList;
    }

    //删除关注
    public void delete(Follower follower) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL语句
            String sql = "delete from followers where userId = ? and followerUserId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, follower.getUserId());
            statement.setInt(2, follower.getFollowerUserId());
            //3.执行sql
            int ret = statement.executeUpdate();
            if (ret == 1) {
                System.out.println("删除成功！");
            } else {
                System.out.println("删除失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }
}
